package top.yokey.android.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import top.yokey.android.R;
import top.yokey.android.base.App;
import top.yokey.android.base.BaseActivity;
import top.yokey.android.base.GlideEngine;
import top.yokey.android.fragment.MineFragment;
import top.yokey.android.http.BaseCallBack;
import top.yokey.android.http.HttpHelp;

public class DynamicAddActivity extends BaseActivity {

    private AppCompatTextView sendTextView;
    private AppCompatEditText contentEditText;
    private AppCompatImageView[] mainImageView = new AppCompatImageView[9];

    private List<LocalMedia> imageList = new ArrayList<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_dynamic_add);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {

        sendTextView = findViewById(R.id.sendTextView);
        contentEditText = findViewById(R.id.contentEditText);
        mainImageView[0] = findViewById(R.id.main1ImageView);
        mainImageView[1] = findViewById(R.id.main2ImageView);
        mainImageView[2] = findViewById(R.id.main3ImageView);
        mainImageView[3] = findViewById(R.id.main4ImageView);
        mainImageView[4] = findViewById(R.id.main5ImageView);
        mainImageView[5] = findViewById(R.id.main6ImageView);
        mainImageView[6] = findViewById(R.id.main7ImageView);
        mainImageView[7] = findViewById(R.id.main8ImageView);
        mainImageView[8] = findViewById(R.id.main9ImageView);

    }

    @Override
    public void initEvent() {

        for (int i = 0; i < mainImageView.length; i++) {
            final int pos = i;
            mainImageView[i].setOnClickListener(view -> {
                //判断是否已经存在图片，从imageList对象获取数据
                if (imageList.size() != 0 && imageList.size() > pos && imageList.get(pos) != null) {
                    //此图片框已经存在图片了
                    new AlertDialog.Builder(this)
                            .setTitle("请选择~")
                            .setMessage("您需要进行的操作")
                            .setCancelable(false)
                            .setPositiveButton("删除", (dialogInterface, m) -> {
                                imageList.remove(pos);
                                handlerImage();
                            })
                            .setNegativeButton("更换", (dialogInterface, m) -> {
                                PictureSelector.create(this)
                                        .openGallery(PictureMimeType.ofImage())
                                        .loadImageEngine(GlideEngine.createGlideEngine())
                                        .maxSelectNum(1)
                                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                                            @Override
                                            public void onResult(List<LocalMedia> result) {
                                                //去重
                                                boolean have = false;
                                                for (int k = 0; k < imageList.size(); k++) {
                                                    if (imageList.get(k).getPath().equals(result.get(0).getPath())) {
                                                        have = true;
                                                    }
                                                }
                                                if (have) {
                                                    Toast.makeText(DynamicAddActivity.this, "重复图片已去除", Toast.LENGTH_SHORT).show();
                                                } else {
                                                    imageList.remove(pos);
                                                    imageList.add(pos, result.get(0));
                                                }
                                                handlerImage();
                                            }

                                            @Override
                                            public void onCancel() {

                                            }
                                        });
                            })
                            .show();
                    return;
                }
                if (pos != imageList.size()) return;
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .loadImageEngine(GlideEngine.createGlideEngine())
                        .maxSelectNum(9 - imageList.size())
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(List<LocalMedia> result) {
                                //去重
                                boolean have = false;
                                for (int j = 0; j < result.size(); j++) {
                                    boolean flag = false;
                                    for (int k = 0; k < imageList.size(); k++) {
                                        if (imageList.get(k).getPath().equals(result.get(j).getPath())) {
                                            have = true;
                                            flag = true;
                                        }
                                    }
                                    if (!flag) {
                                        imageList.add(result.get(j));
                                    }
                                }
                                if (have) {
                                    Toast.makeText(DynamicAddActivity.this, "重复图片已去除", Toast.LENGTH_SHORT).show();
                                }
                                handlerImage();
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
            });
        }

        sendTextView.setOnClickListener(view -> {
            String content = contentEditText.getText().toString();
            if (content.isEmpty()) {
                Toast.makeText(DynamicAddActivity.this, "请输入此刻的想法...", Toast.LENGTH_SHORT).show();
                return;
            }
            sendTextView.setText("发表中...");
            sendTextView.setEnabled(false);
            HttpHelp.get().ready("circle", "add")
                    .add("content", content)
                    .get(new BaseCallBack() {
                        @Override
                        public void onSuccess(String data) {
                            //发表第一步完成之后 data就是 circleId
                            if (imageList.size() == 0) {
                                //未选择图片
                                Toast.makeText(DynamicAddActivity.this, "发表成功", Toast.LENGTH_SHORT).show();
                                finish();
                                return;
                            }
                            uploadImage(data);
                        }

                        @Override
                        public void onFailure(String reason) {
                            Toast.makeText(DynamicAddActivity.this, reason, Toast.LENGTH_SHORT).show();
                            sendTextView.setText("发表");
                            sendTextView.setEnabled(true);
                        }
                    });
        });

    }

    private void handlerImage() {

        for (int i = 0; i < mainImageView.length; i++) {
            mainImageView[i].setImageResource(R.mipmap.ic_add_image_null);
        }
        for (int i = 0; i < imageList.size(); i++) {
            Glide.with(this).load(imageList.get(i).getPath()).into(mainImageView[i]);
        }
        //只选了一张图片的时候 imageList.size 的值就是 1
        //数组下标从0
        if (imageList.size() < 9) {
            mainImageView[imageList.size()].setImageResource(R.mipmap.ic_add_image);
        }

    }

    private void uploadImage(String id) {

        //假设有9张图，imageList.size 9
        //0 1 2 3 4 5 6 7 8
        //调用remove(0)
        //0 1 2 3 4 5 6 7

        if (imageList.size() == 0) {
            Toast.makeText(DynamicAddActivity.this, "发表成功", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        HttpHelp.get().ready("circle", "uploadImage")
                .add("id", id)
                .post(new File(imageList.get(0).getPath()), new BaseCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        imageList.remove(0);
                        uploadImage(id);
                    }

                    @Override
                    public void onFailure(String reason) {

                    }
                });

    }

}
